<template>
  <view class="container">
    <!-- 顶部店铺信息 -->
    <view class="shop-info">
      <view class="shop-logo">
        <image src="/static/shop-logo.png" mode="aspectFit"></image>
      </view>
      <view class="shop-details">
        <view class="shop-name">KKmall京基店2楼188号</view>
        <view class="shop-rating">
          <text class="rating-score">4.8</text>
          <text class="rating-count">月售2000+</text>
        </view>
      </view>
    </view>

    <!-- 分类导航和内容区域 -->
    <view class="content-wrapper">
      <!-- 左侧分类导航 -->
      <scroll-view class="category-nav" scroll-y>
        <view
          v-for="(category, index) in categories"
          :key="index"
          :class="['category-item', activeCategory === index ? 'active' : '']"
          @tap="switchCategory(index)"
        >
          {{ category.name }}
        </view>
      </scroll-view>

      <!-- 右侧菜单列表 -->
      <scroll-view
        class="menu-list"
        scroll-y
        :scroll-top="scrollTop"
        @scroll="onScroll"
        :scroll-into-view="scrollIntoView"
        scroll-with-animation="true"
        show-scrollbar="false"
      >
        <!-- 推荐商品 -->
        <view
          v-for="(category, cIndex) in categories"
          :key="cIndex"
          :id="'category-' + cIndex"
          class="menu-section"
        >
          <!-- 标题  -->
          <view class="section-title">{{ category.name }}</view>
          <view
            v-for="(item, iIndex) in category.items"
            :key="iIndex"
            :class="['menu-item', item.featured ? 'featured' : '']"
          >
            <view class="item-image">
              <image :src="item.image" mode="aspectFill"></image>
              <view v-if="item.isNew" class="new-tag">新品</view>
            </view>
            <view class="item-info">
              <text class="item-name">{{ item.name }}</text>
              <text class="item-desc">{{ item.description }}</text>
              <view class="item-bottom">
                <text class="item-price">¥{{ item.price }}</text>
                <view class="item-actions">
                  <view
                    class="btn-decrease"
                    v-if="getCartCount(item.id) > 0"
                    @tap.stop="decreaseItem(item)"
                    >-</view
                  >
                  <text class="item-count" v-if="getCartCount(item.id) > 0">{{
                    getCartCount(item.id)
                  }}</text>
                  <view class="btn-add" @tap.stop="addToCart(item)">+</view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 占位盒子，防止点击区域不足 -->
        <view style="width: 90rpx; height: 60%"></view>
      </scroll-view>
    </view>
    <!-- 购物车 -->
    <view class="cart-container" v-if="totalCount > 0">
      <view class="cart-info">
        <view class="cart-icon">
          <view class="cart-count">{{ totalCount }}</view>
        </view>
        <view class="cart-price">
          <text class="price-label">合计:</text>
          <text class="price-value">¥{{ totalPrice.toFixed(2) }}</text>
        </view>
      </view>
      <view class="checkout-btn" @tap="checkout">去结算</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import Mock from "mockjs";
import { storeToRefs } from "pinia";
import { useBillStore } from "@/store/bill";
const billStore = useBillStore();
// 数据解构
const { billData } = storeToRefs(billStore);
// 方法解构
const { addBillData } = billStore;
// 使用 Mock.js 生成分类和商品数据
const generateMockData = () => {
  // 定义饮品分类
  const categoryNames = [
    "招牌柠檬茶",
    "生椰系列",
    "酵香奶茶",
    "特色饮品",
    "冰沙系列",
    "热饮系列",
  ];
  // 饮品名称前缀和后缀，用于随机组合生成饮品名称
  const prefixes = [
    "香浓",
    "清爽",
    "醇厚",
    "鲜果",
    "原味",
    "特调",
    "招牌",
    "精选",
    "芝士",
    "奶盖",
  ];
  const mainNames = [
    "柠檬茶",
    "奶茶",
    "拿铁",
    "果茶",
    "乌龙茶",
    "绿茶",
    "红茶",
    "冰茶",
    "椰乳茶",
    "芒果茶",
  ];
  const suffixes = ["(大杯)", "(小杯)", "(热饮)", "(冰饮)", "(少糖)", "(无糖)"];
  // 饮品描述模板
  const descTemplates = [
    "#{taste}口感，#{feature}回味",
    "#{feature}风味，#{taste}可口",
    "采用#{origin}原料，#{taste}怡人",
    "#{origin}特制，#{feature}醇香",
    "#{taste}清爽，#{feature}解渴",
  ];

  // 口感、特点和原料词库
  const tastes = [
    "香浓",
    "清爽",
    "醇厚",
    "甘甜",
    "酸甜",
    "浓郁",
    "淡雅",
    "丝滑",
  ];
  const features = [
    "持久",
    "甘醇",
    "独特",
    "层次丰富",
    "回味无穷",
    "清新",
    "自然",
  ];
  const origins = [
    "进口",
    "本地",
    "新鲜",
    "优质",
    "精选",
    "有机",
    "特级",
    "手工",
  ];

  // 生成随机描述
  const generateDescription = () => {
    const template = Mock.Random.pick(descTemplates);
    return template
      .replace("#{taste}", Mock.Random.pick(tastes))
      .replace("#{feature}", Mock.Random.pick(features))
      .replace("#{origin}", Mock.Random.pick(origins));
  };

  // mockjs生成随机图片路径
  const generateImagePath = (name) => {
    return Mock.Random.dataImage("100x100", name);
  };

  // 生成随机距离
  const generateDistance = () => {
    return `${Mock.Random.integer(100, 800)}m`;
  };

  // 生成分类数据
  let idCounter = 1;
  const mockCategories = [];

  // 随机选择3-6个分类
  const selectedCategories = Mock.Random.shuffle(categoryNames).slice(
    0,
    // Mock.Random.integer(3, 6) 的作用是随机选取3到6个饮品分类
    Mock.Random.integer(3, 6)
  );

  // 为每个选中的分类生成商品数据
  selectedCategories.forEach((categoryName, categoryIndex) => {
    /**
     * 遍历选中的分类，为每个分类生成随机数量的商品
     * @param {string} categoryName - 分类名称
     * @param {number} categoryIndex - 分类索引
     */
    // 每个分类下生成2-6个商品
    const itemCount = Mock.Random.integer(2, 6);
    const items = [];

    for (let i = 0; i < itemCount; i++) {
      /**
       * 循环生成指定数量的商品
       * @param {number} i - 当前商品索引
       */
      // 随机组合生成饮品名称
      const nameComponents = [];
      // 70%概率添加前缀
      if (Mock.Random.boolean(0.7))
        nameComponents.push(Mock.Random.pick(prefixes));
      // 添加主要名称
      nameComponents.push(Mock.Random.pick(mainNames));
      // 30%概率添加后缀
      if (Mock.Random.boolean(0.3))
        nameComponents.push(Mock.Random.pick(suffixes));

      const name = nameComponents.join("");

      // 生成商品数据
      items.push({
        id: idCounter++,
        name,
        price: Mock.Random.integer(15, 30),
        description: generateDescription(),
        image: generateImagePath(name),
        featured: Mock.Random.boolean(0.1), // 10%的概率是特色商品
        isNew: Mock.Random.boolean(0.2), // 20%的概率是新品
        distance: generateDistance(),
      });
    }

    mockCategories.push({
      name: categoryName,
      items,
    });
  });

  // 确保至少有一个特色商品
  if (
    !mockCategories.some((category) =>
      category.items.some((item) => item.featured)
    )
  ) {
    const randomCategory = Mock.Random.pick(mockCategories);
    const randomItem = Mock.Random.pick(randomCategory.items);
    randomItem.featured = true;
  }

  // 确保至少有一个新品
  // Mock.Random.pick() 会随机选择其中一个
  // 检查是否所有分类中都没有isNew为true的商品
  if (
    !mockCategories.some((category) =>
      // 遍历每个分类的商品，检查是否存在isNew为true的商品
      category.items.some((item) => item.isNew)
    )
  ) {
    // 如果没有isNew为true的商品，则随机选择一个分类
    const randomCategory = Mock.Random.pick(mockCategories);
    // 在选中的分类中随机选择一个商品
    const randomItem = Mock.Random.pick(randomCategory.items);
    // 将该商品的isNew属性设置为true
    randomItem.isNew = true;
  }

  return mockCategories;
};

// 生成并引用模拟数据
const categories = ref([]);

// 当前激活的分类索引
const activeCategory = ref(0);

// 滚动相关
const scrollTop = ref(0);
// 目标滚动的元素
const scrollIntoView = ref("");

// 切换分类
const switchCategory = (index) => {
  activeCategory.value = index;
  scrollIntoView.value = `category-${index}`;
};

// 节流函数
const throttle = (fn, delay) => {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
};

// 监听滚动事件，实现联动效果
// 修改onScroll方法 当滚动时，滚动到某一元素时 触发当前分类激活效果
const onScroll = throttle((e) => {
  // 获取所有分类的位置信息
  const query = uni.createSelectorQuery().in(this);
  // 获取当前视口相对于显示区域的高度
  let topH = 0;
  query.select(".shop-info").boundingClientRect((info) => {
    topH = info.bottom;
    // console.log("topH", topH);
  });
  query
    .selectAll(".menu-section") // 选择所有菜单节点的DOM元素
    .boundingClientRect((rects) => {
      // console.log("rects", rects);
      // console.log("e.detail", e);
      // 获取这些元素的位置信息
      if (rects && rects.length > 0) {
        // 确保获取到了有效的位置信息
        // const scrollTop = e.detail.scrollTop; // 获取当前滚动位置
        // 找到当前显示的分类
        const currentCategory = rects.findIndex((rect) => {
          return rect.top - topH < 0 && rect.bottom - topH > 0; // 判断元素是否在可视区域内
        });

        // 如果找到当前分类且与激活的分类不同，则更新激活的分类
        if (
          currentCategory !== -1 && // 确保找到了有效分类
          currentCategory !== activeCategory.value // 确保分类与当前激活的不同
        ) {
          activeCategory.value = currentCategory; // 更新当前激活的分类
        }
      }
    })
    .exec();
}, 16); // 约60fps的节流频率

// 购物车数据
const cartItems = ref([]);

// 购物车相关方法
const addToCart = (item) => {
  // console.log("item", item);
  // 查找购物车中是否已存在该商品
  const existingItem = cartItems.value.find(
    (cartItem) => cartItem.id === item.id
  );
  // 如果存在，则增加数量
  if (existingItem) {
    existingItem.count++;
  } else {
    // 否则，添加新商品到购物车
    cartItems.value.push({
      ...item,
      count: 1,
    });
  }
};
// 减少商品
const decreaseItem = (item) => {
  // 在购物车商品列表中查找与当前商品ID匹配的商品索引
  const index = cartItems.value.findIndex(
    // 使用箭头函数遍历购物车项，查找ID匹配的商品
    (cartItem) => cartItem.id === item.id
  );
  // 如果找到匹配的商品（索引不为-1）
  if (index !== -1) {
    // 如果购物车中该商品的数量大于1
    if (cartItems.value[index].count > 1) {
      // 将该商品的数量减1
      cartItems.value[index].count--;
    } else {
      // 如果商品数量为1，则从购物车中移除该商品
      cartItems.value.splice(index, 1);
    }
  }
};

// 获取购物车内部某一个商品数量
const getCartCount = (itemId) => {
  const item = cartItems.value.find((item) => item.id === itemId);
  return item ? item.count : 0;
};

// 计算购物车总数量
const totalCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.count, 0);
});

// 计算购物车总价格
const totalPrice = computed(() => {
  return cartItems.value.reduce(
    (total, item) => total + item.price * item.count,
    0
  );
});

// 结算方法
const checkout = () => {
  uni.showModal({
    title: "确认订单",
    content: `共${totalCount.value}件商品，合计¥${totalPrice.value.toFixed(2)}`,
    success: function (res) {
      // console.log(res);
      if (res.confirm) {
        // 替换解构调用
        // billStore.addBillData(cartItems); // 直接通过 billStore 调用
        addBillData(cartItems.value, "paid");
        uni.showToast({
          title: "订单已提交",
          icon: "success",
        });
        console.log("成功提交订单", cartItems.value);
        // 这里可以添加提交订单的逻辑
        cartItems.value = [];
      } else {
        addBillData(cartItems.value, "unpaid");
        cartItems.value = [];
        uni.showToast({
          title: "您取消了订单",
          icon: "success",
          duration: 1000,
        });
      }
    },
  });
};

// 页面加载时的初始化
onMounted(() => {
  // 模拟从服务器获取数据的延迟
  uni.showLoading({
    title: "加载中...",
  });

  setTimeout(() => {
    // 重新生成随机数据
    categories.value = generateMockData();
    // console.log("categories.value", categories.value);
    uni.hideLoading();

    // 显示新品上市提示
    const hasNewItems = categories.value.some((category) =>
      category.items.some((item) => item.isNew)
    );

    if (hasNewItems) {
      uni.showToast({
        title: "新品上市",
        icon: "none",
        duration: 2000,
      });
    }
  }, 500);
});
</script>

<style lang="scss">
page {
  height: 100%;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f8f8f8;
}

/* 店铺信息样式 */
.shop-info {
  padding: 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .shop-logo {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
    border-radius: 50%;
    overflow: hidden;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .shop-details {
    flex: 1;

    .shop-name {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 8rpx;
    }

    .shop-rating {
      display: flex;
      align-items: center;

      .rating-score {
        color: #ff9500;
        font-size: 26rpx;
        font-weight: bold;
        margin-right: 10rpx;
      }

      .rating-count {
        color: #999;
        font-size: 24rpx;
      }
    }
  }
}

/* 内容区域布局 */
.content-wrapper {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧分类导航 */
.category-nav {
  width: 160rpx;
  background-color: #f5f5f5;
  height: 100%;

  .category-item {
    padding: 30rpx 10rpx;
    font-size: 26rpx;
    text-align: center;
    position: relative;
    color: #666;

    &.active {
      background-color: #fff;
      color: #ff6b00;
      font-weight: bold;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 36rpx;
        background-color: #ff6b00;
        border-radius: 0 3rpx 3rpx 0;
      }
    }
  }
}

/* 右侧菜单列表 */
.menu-list {
  flex: 1;
  padding: 0 20rpx;
  height: 100%;
}

.menu-section {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);

  .section-title {
    padding: 20rpx;
    font-size: 28rpx;
    font-weight: bold;
    border-bottom: 1rpx solid #f0f0f0;
    background-color: #fff;
    color: #333;
  }
}

.menu-item {
  padding: 25rpx 20rpx;
  display: flex;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;

  &.featured {
    background-color: #fff8e6;
  }

  .item-image {
    /* 设置容器宽度为160rpx */
    width: 160rpx;
    /* 设置容器高度为160rpx */
    height: 160rpx;
    /* 设置容器边框圆角为12rpx */
    border-radius: 12rpx;
    /* 设置容器溢出内容隐藏 */
    overflow: hidden;
    /* 设置容器为相对定位 */
    position: relative;
    /* 设置容器右边距为20rpx */
    margin-right: 20rpx;

    /* 设置图片样式 */
    image {
      /* 设置图片宽度为100% */
      width: 100%;
      /* 设置图片高度为100% */
      height: 100%;
    }

    .new-tag {
      /* 设置元素的定位方式为绝对定位 */
      position: absolute;
      /* 设置元素顶部距离父元素顶部的距离为0 */
      top: 0;
      /* 设置元素左侧距离父元素左侧的距离为0 */
      left: 0;
      /* 设置元素的背景颜色为红色(#ff4d4f) */
      background-color: #ff4d4f;
      /* 设置文字颜色为白色 */
      color: white;
      /* 设置字体大小为20rpx(rpx是微信小程序中的尺寸单位) */
      font-size: 20rpx;
      /* 设置元素的内边距，上下为4rpx，左右为10rpx */
      padding: 4rpx 10rpx;
      /* 设置元素的圆角边框，右下角为10rpx，其余为0 */
      border-radius: 0 0 10rpx 0;
    }
  }

  .item-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .item-name {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      color: #333;
    }

    .item-desc {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 20rpx;
      line-height: 1.4;
    }

    .item-bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .item-price {
        color: #ff6b00;
        font-size: 32rpx;
        font-weight: bold;
      }

      .item-actions {
        display: flex;
        align-items: center;

        .btn-decrease,
        .btn-add {
          width: 50rpx;
          height: 50rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 36rpx;
          line-height: 1;
        }

        .btn-decrease {
          background-color: #fff;
          border: 1rpx solid #ddd;
          color: #666;
        }

        .btn-add {
          background-color: #ff6b00;
          color: #fff;
        }

        .item-count {
          margin: 0 15rpx;
          font-size: 28rpx;
          min-width: 30rpx;
          text-align: center;
        }
      }
    }
  }

  .item-distance {
    font-size: 22rpx;
    color: #999;
    position: absolute;
    top: 25rpx;
    right: 20rpx;
  }
}

/* 购物车样式 */
.cart-container {
  height: 100rpx;
  background-color: #333;
  display: flex;
  align-items: center;
  padding: 0 20rpx;

  .cart-info {
    flex: 1;
    display: flex;
    align-items: center;

    .cart-icon {
      width: 80rpx;
      height: 80rpx;
      background-color: #ff6b00;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      position: relative;

      &::before {
        content: "🛒";
        font-size: 40rpx;
        color: #fff;
      }

      .cart-count {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        background-color: #ff4d4f;
        color: #fff;
        font-size: 20rpx;
        min-width: 36rpx;
        height: 36rpx;
        border-radius: 18rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .cart-price {
      .price-label {
        color: #999;
        font-size: 26rpx;
        margin-right: 10rpx;
      }

      .price-value {
        color: #fff;
        font-size: 32rpx;
        font-weight: bold;
      }
    }
  }

  .checkout-btn {
    background-color: #ff6b00;
    color: #fff;
    font-size: 30rpx;
    padding: 15rpx 40rpx;
    border-radius: 50rpx;
    font-weight: bold;
  }
}
</style>